package middle_ware

import (
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
	"my_music_server/common"
	"my_music_server/common/utils"
	"my_music_server/model"
)

var (
	USER model.User
)

//JWT全局中间件
func JwtTokenMiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		//fmt.Println("jwt in .....")
		//token 存在于前端cookie中，请求会放于请求头
		token := c.GetHeader("auth-token")
		//放行地址列表
		nextMap := map[string]int{
			"/login":                        1,
			"/register":                     1,
			"/test":                         1,
			"/favicon.ico":                  1,
			"/swagger/index.html":           1,
			"/swagger/swagger-ui.css":       1,
			"/swagger/swagger-ui-bundle.js": 1,
			"/swagger/swagger-ui-standalone-preset.js":     1,
			"/swagger/favicon-32x32.png":                   1,
			"/swagger/favicon-16x16.png":                   1,
			"/swagger/swagger-ui.css.map":                  1,
			"/swagger/swagger-ui-bundle.js.map":            1,
			"/swagger/swagger-ui-standalone-preset.js.map": 1,
			"/swagger/doc.json":                            1,
		}

		if _, ok := nextMap[c.Request.URL.Path]; ok {
			//登录接口直接放行
			c.Next()
			//return 禁止再次经过，运行下方代码
			return
		}
		//判断前端传入token是否为空 ，为空拒绝登录
		if token == "" {
			c.Abort()
			panic(common.ERROR_USER_NOLOGIN)
		}

		//验证token合法性
		if !utils.CheckJWT(token) {
			c.Abort()
			panic(common.ERROR_TOKEN_INVALID)
		}

		//解析token【类型断言】
		claims := (utils.ParseJWT(token)).(jwt.MapClaims)
		id := int(claims["id"].(float64))
		nickname := claims["nickname"].(string)
		username := claims["username"].(string)
		sex := int(claims["sex"].(float64))
		phone := claims["phone"].(string)
		headerImgUrl := claims["headerImgUrl"].(string)

		USER = model.User{
			id,
			username,
			nickname,
			"",
			sex,
			phone,
			"",
			headerImgUrl,
		}
		//当前请求后USER需要置空
		defer func() {
			USER = model.User{}
		}()

		//放行
		c.Next()

		//fmt.Println("jwt out .....")
	}
}
